package mrusanov.view

import java.awt.{Graphics2D, Graphics}
import mrusanov.images.Image

class AnimatedSprite(images:Vector[Image], cycle:Boolean = false, centerSprite:Boolean = true) extends Sprite {
  private val SPRITE_SIDE = 72

  private var _index = 0
  private var currentTime = 0
  private var _over = false

  def update(time:Int):Boolean = {
    if (isOver) {
      return false
    }

    if (images.isEmpty) {
      _over = true
      return false
    }

    currentTime += time
    if (currentTime < frameTime) {
      return false
    }

    val times = currentTime / frameTime

    // TODO times can be bigger than frame rate, however this case is not likely to happen
    if (times % 2 == 1 && _index == images.size - 1 && !cycle) {
      _over = true
      return true
    }

    if (times % 2 == 1 ) {
      _index += 1
      _index %= images.size
      return true
    }

    _index %= images.size

    currentTime %= frameTime
    false
  }

  def reset() {
    _index = 0
    currentTime = 0
  }

  def index = _index
  def isOver = _over

  def render(g:Graphics2D) {
    if (images.isEmpty) {
      return
    }

    val image = images(index)
    if (centerSprite) {

      val xCorrection = (SPRITE_SIDE - image.width) / 2
      val yCorrection = (SPRITE_SIDE - image.height) / 2
      image.render(g, xCorrection + x, yCorrection + y)
    } else {
      image.render(g, x, y)
    }
  }
}
